/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hoja5;

/**
 *
 * @author luisorozco
 */

//Clase obtenida del libro de Java Structure

public class CircularQueue<T> extends AQueue<T> {

    //Atributos
    protected Node<T> tail;
    protected int count;

    //Constructor
    public CircularQueue() 
    //Pre: Constructs a new circular list
    {
        tail = null;
        count = 0;
    }    

    @Override
    public void add(T value) 
    //Pre: value non-null
    //Post: adds element to tail of list
    {
        Node<T> temp = new Node<T>(value);
        
        if (tail == null) { //First value added
            tail = temp;
            tail.setNext(tail);
        } else { //Element exists in list
            temp.setNext(tail.next());
            tail.setNext(temp);
        }
        count++;
        
        tail = tail.next();
    }

    @Override
    public T poll() //Post: returns the first element of the list or null
    {
        Node <T> temp = tail;
        
        if (isEmpty()) {
            return null;
        } else {
            while(temp.next() != tail) {
                temp = temp.next();
            }                
            Node <T> temp2 = tail;
            
            if (temp == tail)
                tail = null;
            else {
                temp.setNext(tail.next());
                tail = temp;
            }
            count--;
            return temp2.getValue();    
        } 
    }
    
    
    @Override
    public int size() // post: returns number of elements in list
    {
        return count;
    }

    @Override
    public boolean isEmpty() // post: returns true if the list is empty
    {
        return 0 == count;
    }
}
